<template>
  <view class="x-pop-box" v-if="detail && visible">
    <x-modal :visible.sync="visible" background="transparent" is-cancel width="600" padding="0" @cancel="onCancel">
      <view v-if="detail.linkType !== 23" class="m-groups-modal" @click="onMask" @touchmove.stop.prevent="moveHandle">
        <channel-live v-if="detail.styleType === 1" :feed-id="feedId" :finder-user-name="detail.channelsId" />
        <x-image v-else :src="detail.backgroundUrl" show-long-press mode="widthFix" @longPress="longPress"/>
      </view>
      <!--  优惠券领取  -->
      <view v-if="detail.linkType === 23 && detail.couponInfos" class="m-groups-modal">
        <send-coupon
          :send_coupon_params="detail.couponInfos.send_coupon_params"
          :sign="detail.couponInfos.sign"
          :send_coupon_merchant="detail.couponInfos.send_coupon_merchant"
          @sendcoupon="onCustomEvent"
        >
          <view>
            <x-image :src="detail.backgroundUrl" mode="widthFix" />
          </view>
        </send-coupon>
      </view>
    </x-modal>
  </view>
</template>

<script>
import navigate from '@/utils/x-navigate';
import XModal from '@/components/x-modal';
import XImage from '@/components/x-image';
export default {
  name: 'XPopBox',
  components: { XImage, XModal },
  props: {
    query: {
      type: Object,
      default: () => {}
    },
    boxId: {
      type: [String, Number],
      default: ''
    },
    storeId: {
      type: [String, Number],
      default: ''
    },
    triggerType: {
      type: [String, Number],
      default: 1
    }

  },
  data() {
    return {
      visible: false,
      storageActivityDetail: null,
      feedId: '',
      nonceId: '',
      noticeInfo: {},
      detail: {}
    };
  },
  computed: {
    // 匹配当前页面对应缓存数据
    currentStorageDetail() {
      return this.storageActivityDetail && this.storageActivityDetail[this.currentRoute];
    }
  },
  created() {
    this.getStorageActivityDetail();
    this.getDetail();
  },
  mounted() {

  },
  onLoad(query) {
    this.query = query;
  },
  watch: {},
  methods: {
    longPress() {
      this.$XTrack('onPopupBoxLongPressEvent', { id: this.detail.id });
    },
    moveHandle() {},
    onMask() {
      this.$XTrack('onPopupBoxEvent', { id: this.detail.id });
      this.$store.dispatch('pages/setData', {
        payCancelTwoVisible: false
      });
      this.visible = false;
      const sourcePageType = this.query?.sourcePageType;
      const sourcePageId = this.query?.sourcePageId;
      const source = this.query?.source;
      const sourceFrom = this.query?.sourceFrom;
      const groupsSource = this.query?.groupsSource;

      if (this.detail.styleType === 2 && this.detail.channelsId) {
        this.handleWatchLive();
        return false;
      }

      if (!this.detail.linkContent) {
        return false;
      }
      navigate(this.detail, {
        sourcePageType: sourcePageType,
        sourcePageId: sourcePageId,
        source: source,
        sourceFrom: sourceFrom,
        groupsSource: groupsSource
      });
      // navigate(this.detail, sourcePageType, sourcePageId, source, sourceFrom);
      this.$emit('cancel');
    },
    onCancel() {
      this.visible = false;
      this.$emit('cancel');
      this.$XTrack('onCancelPopupBoxEvent', 'cancel');
    },
    getStorageActivityDetail() {
      try {
        this.currentRoute = this.$getCurrPage().route.replace(/\//gi, '-');
        // 获取所有缓存数据
        this.storageActivityDetail = uni.getStorageSync('storage-activity-detail') || {};
      } catch (e) {
        console.log(e);
      }
    },
    // 获取当前页面对象
    $getCurrPage() {
      const pages = getCurrentPages();
      return pages[pages.length - 1];
    },
    getDetail() {
      const params = {
        triggerType: this.triggerType
      };
      if ([2, 3, 5, 6, 10].includes(this.triggerType)) {
        params.storeId = this.storeId;
      }
      if ([3, 4, 5, 6].includes(this.triggerType)) {
        params.id = this.boxId;
      }
      // // 当前缓存的弹层id
      // if (this.currentStorageDetail && this.currentStorageDetail.id) {
      //   params.previousPopupBoxId = this.currentStorageDetail.id;
      // }
      this.$http({
        url: '/product/popup/box/app/list',
        data: params,
        report: true,
        alarm: true
      }).then(async res => {
        this.handleItem(res.data);
      });
    },
    // 处理当前弹层
    async handleItem(resData) {
      const list = resData || [];
      this.detail = this.getItem(list);
      const data = this.detail;
      if (this.detail?.id) {
        // 校验显示频率信息
        if (this.getIsShowFrequency(data)) {
          if ([1, 2].includes(this.detail?.styleType) && this.detail.channelsId) {
            try {
              const { status, success } = await this.getChannelsLiveInfo();
              if (!success || (!this.detail.liveNotice && !this.detail.endShow && status === 3)) {
                const filteredList = list.filter(item => item.id !== this.detail.id);
                if (filteredList.length === 0) {
                  return;
                }
                this.handleItem(filteredList);
                return;
              }
            } catch (e) {
              console.log('获取直播信息失败', e);
              return;
            }
          }
          this.visible = true;
          const oldId = this.currentStorageDetail?.oldId || [];
          if (!oldId?.includes(data.id)) {
            oldId.push(data.id);
          }
          // 缓存当前活动显示频率信息
          this.storageActivityDetail[this.currentRoute] = {
            oldId: oldId,
            id: data.id,
            triggerType: data.triggerType,
            showFrequency: data.showFrequency,
            date: +new Date(),
            boxId: this.boxId
          };
          uni.setStorageSync('storage-activity-detail', this.storageActivityDetail);
          this.$emit('isNewPop');
          // pv埋点
          this.$XTrack('popupBoxShow', {
            id: data.id
          });
        }
      }
    },

    getNextItem(list, lastId) {
      const lastIndex = list.findIndex(item => item.id === lastId);
      const nextIndex = lastIndex + 1;
      if (nextIndex > list.length - 1) {
        return list[0];
      } else {
        return list[nextIndex];
      }
    },

    // 获取当前弹层
    getItem(data) {
      if (data.length > 0) {
        const date = +new Date();
        const storageDetail = this.currentStorageDetail;
        // 只要存在新的id就展示
        for (let i = 0; i < data.length; i++) {
          if (!this.currentStorageDetail?.oldId?.includes(data[i].id)) {
            return data[i];
          }
        }

        const nextItem = this.getNextItem(data, storageDetail?.id);
        return nextItem;
        // if (nextItem.showFrequency === 1) {
        //   return nextItem;
        // } else if (nextItem.showFrequency === 2) {
        //   const index = data.length - (data.length - j);
        //   return data[index];
        // } else if (data[j].showFrequency === 3 && date - (storageDetail?.date || 0) > 1000 * 60 * 60 * 24 * 7) {
        //   const index = data.length - (data.length - j);
        //   return data[index];
        // }

        // for (let j = 0; j < data.length; j++) {
        //   if (this.currentStorageDetail?.oldId?.includes(data[j].id)) {
        //     if (data[j].showFrequency === 1) {
        //       return j >= data.length - 1 ? data[0] : data[j + 1];
        //     } else if (data[j].showFrequency === 2 && date - (storageDetail?.date || 0) > 1000 * 60 * 60 * 24) {
        //       const index = data.length - (data.length - j);
        //       return data[index];
        //     } else if (data[j].showFrequency === 3 && date - (storageDetail?.date || 0) > 1000 * 60 * 60 * 24 * 7) {
        //       const index = data.length - (data.length - j);
        //       return data[index];
        //     }
        //   } else {
        //     return data[j];
        //   }
        // }
      }
    },
    // 校验是否存在相同值
    isRepeat(arr) {
      const array = [];
      arr.forEach((item) => {
        if (item.showFrequency === 1) {
          array.push(item);
        }
      });
      if (array.length > 1) {
        return true;
      }
      return false;
    },
    // 校验显示频率信息
    getIsShowFrequency(data) {
      const storageDetail = this.currentStorageDetail;
      // const data = this.detail;
      if (
        (storageDetail &&
        storageDetail.id === data.id &&
        storageDetail.triggerType === data.triggerType &&
        storageDetail.showFrequency === data.showFrequency &&
        [2, 3].includes(data.showFrequency)) ||
        !this.currentStorageDetail?.oldId?.includes(data.id)
      ) {
        if (data.showFrequency === 1) {
          return true;
        }
        const date = +new Date();
        // 每天一次
        if (data.showFrequency === 2) {
          // console.log(1);
          // 如果缓存时间大于24小时，直接显示
          if (date - (storageDetail?.date || 0) > 1000 * 60 * 60 * 24 || !this.currentStorageDetail?.oldId?.includes(data.id)) {
            return true;
          }
          const current = new Date().getDate();
          const old = new Date(storageDetail?.date).getDate();
          // 小于24小时，校验是否隔天
          return current !== old;
        } else {
          // console.log(2);
          // 每周一次
          // 如果缓存时间大于7天，直接显示
          if (date - (storageDetail?.date || 0) > 1000 * 60 * 60 * 24 * 7 || !this.currentStorageDetail?.oldId?.includes(data.id)) {
            return true;
          }
          const current = new Date().getDay();
          const old = new Date(storageDetail?.date).getDay();
          // 小于7天，校验是否隔周
          return current !== old && current === 1;
        }
      } else {
        // console.log(3);
        // 每次，小程序没有onHide之前，所有id只弹出一次
        const list = this.storageActivityDetail['show-list'] || [];
        if (!list.includes(data.triggerType)) {
          // console.log(4);
          list.push(data.triggerType);
          this.storageActivityDetail['show-list'] = list;
          uni.setStorageSync('storage-activity-detail', this.storageActivityDetail);
          return true;
        } else {
          // console.log(5);
          const date = +new Date();
          // 每次启动都显示
          // return false;
          if (data.showFrequency === 1) {
            // console.log(0);
            return true;
          } else if (data.showFrequency === 2 && date - (storageDetail?.date || 0) > 1000 * 60 * 60 * 24) {
            return true;
          } else if (data.showFrequency === 3 && date - (storageDetail?.date || 0) > 1000 * 60 * 60 * 24 * 7) {
            return true;
          } else {
            return false;
          }
        }
      }
    },
    // 领取优惠券并下单
    onCustomEvent(res) {
      this.visible = false;
      if (res.detail.errcode === 'OK') {
        // 通知服务端
        if (res.detail.send_coupon_result[0].coupon_code) {
          const allCoupon = [];
          for (let i = 0; i < res.detail.send_coupon_result.length; i++) {
            allCoupon.push({
              couponCode: res.detail.send_coupon_result[i].coupon_code,
              stockId: res.detail.send_coupon_result[i].stock_id
            });
          }
          const params = {
            couponList: allCoupon
          };
          this.$http({
            report: true,
            method: 'post',
            url: '/marketing/user/coupon/save/batch',
            data: params
          }).then((result) => {
            this.$XTrack('onCustomSaveBatch');
          }).catch(() => {
          });
        }
      }
      this.$XTrack('onPoPBoxCouponEvent', {
        code: res.detail.errcode,
        id: this.detail.id
      });
    },

    getChannelsLiveInfo() {
      return new Promise((resolve, reject) => {
        uni.getChannelsLiveInfo({
          finderUserName: this.detail.channelsId,
          success: (res) => {
            this.feedId = res.feedId;
            this.nonceId = res.nonceId;
            this.status = res.status; // 2直播中 3直播结束

            resolve({ ...res, success: true });

            if (res.status === 3 && this.detail.liveNotice) {
              this.getChannelsLiveNoticeInfo();
            }
          },
          fail: () => {
            resolve({ success: false });
          }
        });
      });
    },
    getChannelsLiveNoticeInfo() {
      uni.getChannelsLiveNoticeInfo({
        finderUserName: this.detail.channelsId,
        success: (res) => {
          this.noticeInfo = res;
        },
        fail: () => {
          console.log('获取直播预约失败');
        }
      });
    },
    handleWatchLive() {
      if (this.noticeInfo.noticeId) {
        // 预约直播
        uni.reserveChannelsLive({
          noticeId: this.noticeInfo.noticeId
        });
      } else {
        uni.openChannelsLive({
          finderUserName: this.detail.channelsId,
          feedId: this.feedId,
          nonceId: this.nonceId,
          success: (res) => {
            console.log(res);
          },
          fail: (err) => {
            console.log(err);
          }
        });
      }
    }
  }
};
</script>

<style lang="scss" scoped>

</style>
